<?php

use console\db\Migration;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\db\Query;

/**
 * 追加动态中有图片的至图库表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000005_t_sns_dynamic_gallery_append extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_gallery}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%ts_dynamic_gallery}}')->orderBy([
            'dynamic_id' => SORT_ASC
        ]);
        $this->handleProgress($query, [$this, 'evenDule'], null, Yii::$app->olddb);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        $path = parse_url($data['image']);
        if (isset($path['host']) && $path['host'] == 'img.lnts.cn' && isset($path['path'])) {
            $data['image'] = $path['path'];
        }
        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        $items = [];
        $dynamicids = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            $dynamicid = $row['dynamic_id'];
            $temp = ArrayHelper::getValue($dynamicids, $dynamicid);
            if ($temp === null) {
                $temp = (new Query())->from('{{%sns_dynamic}}')->select(['id', 'user_id'])->where([
                    'group_id' => 2,
                    'topic_id' => $dynamicid,
                ])->one();
                $dynamicids[$dynamicid] = $temp;
            }
            if (empty($temp)) {
                continue;
            }

            if ($row['image'] && strpos($row['image'], 'http') === false) {
                $row['image'] = '/uploads/' . ltrim($row['image'], '/');
            }
            
            $items[] = [
                'dynamic_id' => $temp['id'],
                'user_id' => $temp['user_id'],
                'original' => $row['image'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
            ];
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%sns_dynamic_gallery}}', [
            'dynamic_id',
            'user_id',
            'original',
            'created_at',
            'updated_at',
        ], $items)->execute();
    }

}
